/**
 * @Description: 这里的api模仿 vuex-pathify, 考虑到vuex-pathify暂时还未有3.x版本，自己写了一套兼容3.x的
 * @Author BPF
 * @create 2021/8/20 10:43
 */
import { computed, toRefs } from 'vue'

var vuexHelper = {
  store: null,
  plugins: function () {
    return store => {
      console.log('vuexHelper-helper.js', store, this)
      this.store = store
    }
  }
}

/**
 * 动态获取vuex里面的state值
 * @param {string} path
 * @returns {WritableComputedRef<*>}
 */
const sync = function (path = '') {
  const { store } = vuexHelper
  if (!path) {
    throw new Error('传入的路径path 不能为空')
  }
  return computed({
    get: () => {
      return path.split('/').reduce((pre, cur) => {
        return pre[cur]
      }, store.state)
    },
    set: val => {
      store.commit(path, val)
    }
  })
}

/**
 *
 * @param path
 * @returns {WritableComputedRef<string>}
 */
const get = function (path = '') {
  const { store } = vuexHelper
  if (!path) {
    throw new Error('传入的路径path 不能为空')
  }
  return computed({
    get: () => {
      return path.split('/').reduce((pre, cur) => {
        return pre[cur]
      }, store.state)
    },
    set: () => {
      console.error('当前的vuex中的state处于readonly，如果想修改其值，请使用sync')
    }
  })
}

/**
 *
 * @param path
 * @returns {*}
 */
const call = function (path = '') {
  if (!path) {
    throw new Error('传入的路径path 不能为空')
  }
  const { store } = vuexHelper
  const action = store._actions[path]?.slice?.()?.shift()
  if (!action) {
    console.error(`action对应的${path}不存在`)
  }
  return action
}

/**
 *
 * @type {{mutations(*=): *}}
 */
const make = {
  mutations(state) {
    return Object.keys(state).reduce((pre, cur) => {
      return {
        ...pre,
        [cur]: function (state, data) {
          state[`${cur}`] = data
        }
      }
    }, {})
  }
}

export default vuexHelper
export { make, sync, get, call }
